package com.applozic.mobicomkit.uiwidgets.conversation.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.FileProvider;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.applozic.mobicomkit.ChatConfig;
import com.applozic.mobicomkit.api.MobiComKitConstants;
import com.applozic.mobicomkit.api.attachment.AttachmentManager;
import com.applozic.mobicomkit.api.attachment.AttachmentView;
import com.applozic.mobicomkit.api.attachment.FileClientService;
import com.applozic.mobicomkit.api.attachment.FileMeta;
import com.applozic.mobicomkit.api.conversation.Message;
import com.applozic.mobicomkit.api.conversation.MobiComConversationService;
import com.applozic.mobicomkit.api.conversation.database.MessageDatabaseService;
import com.applozic.mobicomkit.contact.BaseContactService;
import com.applozic.mobicomkit.contact.MobiComVCFParser;
import com.applozic.mobicomkit.contact.VCFContactData;
import com.applozic.mobicomkit.uiwidgets.AlCustomizationSettings;
import com.applozic.mobicomkit.uiwidgets.attachmentview.ApplozicDocumentView;
import com.applozic.mobicomkit.uiwidgets.conversation.ConversationUIService;
import com.applozic.mobicomkit.uiwidgets.conversation.activity.ConversationActivity;
import com.applozic.mobicomkit.uiwidgets.conversation.activity.FullScreenImageActivity;
import com.applozic.mobicomkit.uiwidgets.conversation.activity.MobiComKitActivityInterface;
import com.applozic.mobicommons.commons.core.utils.LocationUtils;
import com.applozic.mobicommons.commons.core.utils.Utils;
import com.applozic.mobicommons.commons.image.ImageCache;
import com.applozic.mobicommons.commons.image.ImageLoader;
import com.applozic.mobicommons.emoticon.EmojiconHandler;
import com.applozic.mobicommons.emoticon.EmoticonUtils;
import com.applozic.mobicommons.file.FileUtils;
import com.applozic.mobicommons.json.GsonUtils;
import com.applozic.mobicommons.people.channel.Channel;
import com.applozic.mobicommons.people.contact.Contact;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.GiveRewardActivity;
import com.lottery.ruok.lottrey.activity.LoginActivity;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.eventbusObject.GrabRedPacketSucess;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GrabGiftRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GrabGiftResponse;
import com.lottery.ruok.lottrey.ui.component.BaseRelativeLayout;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import de.hdodenhof.circleimageview.CircleImageView;
import glideHelp.GlideHelper;

/**
 * 其他消息view
 */
public class MobicomSendMessageView extends BaseRelativeLayout {

    private View messageTextLayout;
    private TextView messageTextView;
    private CircleImageView myAvatar;
    private CircleImageView contactImage;
    private ImageView sentOrReceived;
    private ImageView mapImageView;
    private LinearLayout nameTextLayout;
    private RelativeLayout chatLocation;
    private TextView deliveryStatus;
    private TextView selfDestruct;
    private ImageView preview;
    private AttachmentView attachmentView;
    private TextView attachedFile;
    private ImageView attachmentIcon;
    private TextView downloadSizeTextView;
    private LinearLayout attachmentDownloadLayout;
    private LinearLayout attachmentRetry;
    private RelativeLayout attachmentDownloadProgressLayout;
    private RelativeLayout mainAttachmentLayout;
    private LinearLayout mainContactShareLayout;
    private ImageView videoIcon;
    private TextView audio_duration_textView;
    private Message message;
    private BaseContactService contactService;
    private boolean individual;
    private Contact contact;
    private Channel channel;
    private AlCustomizationSettings alCustomizationSettings;
    private ImageCache imageCache;
    private FileClientService fileClientService;
    private ImageLoader imageThumbnailLoader;
    private MessageDatabaseService messageDatabaseService;
    private MobiComConversationService conversationService;
    private Class<?> messageIntentClass;
    private ImageLoader loadImage;
    private EmojiconHandler emojiconHandler;
    private String searchString;
    private TextAppearanceSpan highlightTextSpan;

    public MobicomSendMessageView(Context context) {
        super(context);
    }

    public MobicomSendMessageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MobicomSendMessageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void init(Context context, AttributeSet attrs, int defStyleAttr) {

    }

    @Override
    protected void initView(Context context) {
        setContentView(R.layout.mobicom_sent_message_list_view);
        messageTextLayout = findViewById(R.id.messageTextLayout);
        messageTextView = findViewById(R.id.message);
        myAvatar = findViewById(R.id.my_avatar);
        contactImage = findViewById(R.id.contactImage);
        sentOrReceived = findViewById(R.id.sentOrReceivedIcon);
        mapImageView = findViewById(R.id.static_mapview);
        nameTextLayout = findViewById(R.id.nameTextLayout);
        chatLocation = findViewById(R.id.chat_location);
        deliveryStatus = findViewById(R.id.status);
        selfDestruct = findViewById(R.id.selfDestruct);
        preview = findViewById(R.id.preview);
        attachmentView = findViewById(R.id.main_attachment_view);
        attachedFile = findViewById(R.id.attached_file);
        attachmentIcon = findViewById(R.id.attachmentIcon);
        downloadSizeTextView = findViewById(R.id.attachment_size_text);
        attachmentDownloadLayout = findViewById(R.id.attachment_download_layout);
        attachmentRetry = findViewById(R.id.attachment_retry_layout);
        attachmentDownloadProgressLayout = findViewById(R.id.attachment_download_progress_layout);
        mainAttachmentLayout = findViewById(R.id.attachment_preview_layout);
        mainContactShareLayout = findViewById(R.id.contact_share_layout);
        videoIcon = findViewById(R.id.video_icon);
        audio_duration_textView = findViewById(R.id.audio_duration_textView);
    }

    @Override
    protected void load(Context context) {

    }


    public void setData(Message message, BaseContactService contactService, boolean individual,
                        Contact contact, Channel channel, AlCustomizationSettings alCustomizationSettings,
                        ImageCache imageCache, FileClientService fileClientService, ImageLoader imageThumbnailLoader,
                        MessageDatabaseService messageDatabaseService, MobiComConversationService conversationService,
                        Class<?> messageIntentClass, ImageLoader loadImage, EmojiconHandler emojiconHandler,
                        String searchString, TextAppearanceSpan highlightTextSpan) {
        this.message = message;
        this.contactService = contactService;
        this.individual = individual;
        this.contact = contact;
        this.channel = channel;
        this.alCustomizationSettings = alCustomizationSettings;
        this.imageCache = imageCache;
        this.fileClientService = fileClientService;
        this.imageThumbnailLoader = imageThumbnailLoader;
        this.messageDatabaseService = messageDatabaseService;
        this.conversationService = conversationService;
        this.messageIntentClass = messageIntentClass;
        this.loadImage = loadImage;
        this.emojiconHandler = emojiconHandler;
        this.searchString = searchString;
        this.highlightTextSpan = highlightTextSpan;


        messageTextView.setVisibility(GONE);
        attachmentDownloadLayout.setVisibility(GONE);
        mainAttachmentLayout.setVisibility(View.GONE);
        mainContactShareLayout.setVisibility(View.GONE);
        chatLocation.setVisibility(View.GONE);


        if (message != null) {
            Contact contactDisplayName = null;
            if (message.getGroupId() == null) {
                List<String> items = Arrays.asList(message.getContactIds().split("\\s*,\\s*"));
                List<String> userIds = null;
                if (!TextUtils.isEmpty(message.getContactIds())) {
                    userIds = Arrays.asList(message.getContactIds().split("\\s*,\\s*"));
                }
                if (individual) {
                    if (items.size() > 0) {
                        contact.setContactNumber(items.get(0));
                    }
                    if (userIds != null && userIds.size() > 0) {
                        contact.setUserId(userIds.get(0));
                    }
                }
            } else {
                if (!TextUtils.isEmpty(message.getContactIds())) {
                    contactDisplayName = contactService.getContactById(message.getContactIds());
                }
            }

            if (message.getContentType() == Message.ContentType.LOCATION.getValue() || message.getContentType() == Message.ContentType.ATTACHMENT.getValue()) {
                messageTextLayout.setBackgroundResource(0);
            } else if (message.getContentType() == Message.ContentType.AUDIO_MSG.getValue()) {
                messageTextView.setVisibility(View.GONE);
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) messageTextLayout.getLayoutParams();
                layoutParams.leftMargin = Utils.dpToPx(90);
                messageTextLayout.setLayoutParams(layoutParams);
            }

            if (contactImage != null) {
                final Contact contact1 = contactDisplayName;
                contactImage.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (MobicomSendMessageView.this.message == null || contact1 == null) {
                            return;
                        }
                        gotoGivePrize(MobicomSendMessageView.this.message, contact1);
                    }
                });
            }

            if (audio_duration_textView != null) {
                audio_duration_textView.setTextColor(Color.parseColor("#ffffff"));
//
            }

            final ProgressBar mediaDownloadProgressBar = findViewById(R.id.media_download_progress_bar);
            final ProgressBar mediaUploadProgressBar = findViewById(R.id.media_upload_progress_bar);
            TextView nameTextView = findViewById(R.id.name_textView);
            ImageView uploadDownloadImage = findViewById(R.id.applozic_download_image);
            uploadDownloadImage.setImageResource(R.mipmap.downloadsayright);
            if (TextUtils.isEmpty(message.getMessage())) {
                messageTextView.setVisibility(View.GONE);
            }
            if (attachedFile != null) {
                attachedFile.setText("");
                attachedFile.setVisibility(View.GONE);
            }

            if (attachmentIcon != null) {
                attachmentIcon.setVisibility(View.GONE);
            }

            if (channel != null && nameTextView != null && contactDisplayName != null) {
                nameTextView.setVisibility(Channel.GroupType.GROUPOFTWO.getValue().equals(channel.getType()) ? View.GONE : View.VISIBLE);
                if (alCustomizationSettings.isLaunchChatFromProfilePicOrName()) {
                    nameTextView.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(mContext, ConversationActivity.class);
                            intent.putExtra(ConversationUIService.USER_ID, MobicomSendMessageView.this.message.getContactIds());
                            if (MobicomSendMessageView.this.message.getConversationId() != null) {
                                intent.putExtra(ConversationUIService.CONVERSATION_ID, MobicomSendMessageView.this.message.getConversationId());
                            }
                            mContext.startActivity(intent);
                        }
                    });
                }
                String userId = contactDisplayName.getDisplayName();
                if (userId.length() > 0) {
                    nameTextView.setText(String.valueOf(userId));
                }
            }

            attachmentDownloadLayout.setVisibility(View.GONE);
            preview.setVisibility(message.hasAttachment() ? View.VISIBLE : View.GONE);
            attachmentView.setVisibility(View.GONE);
            if (message.isTypeOutbox() && !message.isCanceled()) {
                mediaUploadProgressBar.setVisibility(message.isAttachmentUploadInProgress() ? View.VISIBLE : View.GONE);
            } else {
                mediaUploadProgressBar.setVisibility(View.GONE);
            }
            if (attachedFile != null) {
                attachedFile.setVisibility(message.hasAttachment() ? View.VISIBLE : View.GONE);
            }

            if (individual && message.getTimeToLive() != null) {
                selfDestruct.setText("Self destruct in " + message.getTimeToLive() + " mins");
                selfDestruct.setVisibility(View.VISIBLE);
            } else {
                selfDestruct.setText("");
                selfDestruct.setVisibility(View.GONE);
            }

            if (sentOrReceived != null) {
                if ((!message.isCall()) || message.isDummyEmptyMessage()) {
                    sentOrReceived.setVisibility(View.GONE);
                } else if (message.isCall()) {
                    sentOrReceived.setImageResource(R.drawable.applozic_ic_action_call_holo_light);
                } else {
                    sentOrReceived.setImageResource(R.drawable.mobicom_social_reply);
                }

                if (message.isCall()) {
                    messageTextView.setTextColor(mContext.getResources().getColor(message.isIncomingCall() ? R.color.incoming_call : R.color.outgoing_call));
                }
            }

            if (nameTextLayout != null && contact != null) {
                nameTextLayout.setVisibility(View.GONE);
            }

            if (message.isCall()) {
                deliveryStatus.setText("");
            }
            if (contactDisplayName != null && contactImage != null && alCustomizationSettings.isLaunchChatFromProfilePicOrName()) {
                contactImage.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(mContext, ConversationActivity.class);
                        intent.putExtra(ConversationUIService.USER_ID, MobicomSendMessageView.this.message.getContactIds());
                        if (MobicomSendMessageView.this.message.getConversationId() != null) {
                            intent.putExtra(ConversationUIService.CONVERSATION_ID, MobicomSendMessageView.this.message.getConversationId());
                        }
                        mContext.startActivity(intent);
                    }
                });
            }
            if (message.isTypeOutbox()) {
                GlideHelper.loadImage(getContext().getApplicationContext(), UserInfo.getAvatar(), myAvatar, R.mipmap.chat_default);
            } else {
                GlideHelper.loadImage(getContext().getApplicationContext(), contactService.getContactById(message.getContactIds()).getImageURL(), contactImage, R.mipmap.chat_default);
            }

            final ApplozicDocumentView audioView = new ApplozicDocumentView(mContext);
            if (message.getContentType() == Message.ContentType.AUDIO_MSG.getValue()) {
                setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        audioView.soundLogic();
                    }
                });
            }
            audioView.inflateViewWithMessage(MobicomSendMessageView.this, message);
            audioView.hideView(true);
            if (message.hasAttachment() && attachedFile != null & !(message.getContentType() == Message.ContentType.TEXT_URL.getValue())) {
                mainAttachmentLayout.setLayoutParams(getImageLayoutParam(false));
                if (message.getFileMetas() != null && (message.getFileMetas().getContentType().contains("image") || message.getFileMetas().getContentType().contains("video"))) {
                    attachedFile.setVisibility(View.GONE);
                }
                if (message.isAttachmentDownloaded()) {
                    preview.setVisibility(View.GONE);
                    for (final String filePath : message.getFilePaths()) {
                        final String mimeType = FileUtils.getMimeType(filePath);
                        if (mimeType != null && mimeType.startsWith("image")) {
                            attachmentView.setMessage(message);
                            attachmentView.setProressBar(mediaDownloadProgressBar);
                            attachmentView.setDownloadProgressLayout(attachmentDownloadProgressLayout);
                            attachmentView.setVisibility(View.VISIBLE);
                            attachedFile.setVisibility(View.GONE);
                        } else if (mimeType != null && mimeType.startsWith("video")) {
                            preview.setVisibility(View.VISIBLE);
                            videoIcon.setVisibility(View.VISIBLE);
                            attachmentDownloadLayout.setVisibility(View.GONE);
                            attachedFile.setVisibility(View.GONE);
                            if (imageCache.getBitmapFromMemCache(message.getKeyString()) != null) {
                                preview.setImageBitmap(imageCache.getBitmapFromMemCache(message.getKeyString()));
                            } else {
                                imageCache.addBitmapToCache(message.getKeyString(), fileClientService.createAndSaveVideoThumbnail(filePath));
                                preview.setImageBitmap(fileClientService.createAndSaveVideoThumbnail(filePath));
                            }
                        } else {
                            showAttachmentIconAndText(attachedFile, message, mimeType);
                        }
                    }
                } else if (message.isAttachmentUploadInProgress()) {
                    attachmentDownloadProgressLayout.setVisibility(View.VISIBLE);
                    attachmentView.setProressBar(mediaDownloadProgressBar);
                    attachmentView.setDownloadProgressLayout(attachmentDownloadProgressLayout);
                    attachmentView.setMessage(message);
                    attachmentView.setVisibility(View.VISIBLE);
                } else if (AttachmentManager.isAttachmentInProgress(message.getKeyString())) {
                    attachmentView.setMessage(message);
                    attachmentView.setVisibility(View.VISIBLE);
                    attachmentView.setProressBar(mediaDownloadProgressBar);
                    attachmentView.setDownloadProgressLayout(attachmentDownloadProgressLayout);
                    showPreview(message, preview, attachmentDownloadLayout);
                    FileMeta fileMeta = message.getFileMetas();
                    final String mimeType = FileUtils.getMimeType(fileMeta.getName());
                    if (!fileMeta.getContentType().contains("image") && !fileMeta.getContentType().contains("video")) {
                        showAttachmentIconAndText(attachedFile, message, mimeType);
                    }
                    downloadSizeTextView.setText(fileMeta.getSizeInReadableFormat());
                    attachmentView.setDownloadProgressLayout(attachmentDownloadProgressLayout);
                    attachmentDownloadProgressLayout.setVisibility(View.VISIBLE);
                } else {
                    showPreview(message, preview, attachmentDownloadLayout);
                    if (message.getFileMetas() != null) {
                        FileMeta fileMeta = message.getFileMetas();
                        attachmentDownloadLayout.setVisibility(View.VISIBLE);
                        attachmentDownloadProgressLayout.setVisibility(View.GONE);
                        downloadSizeTextView.setText(fileMeta.getSizeInReadableFormat());
                        final String mimeType = FileUtils.getMimeType(fileMeta.getName());
                        if (!fileMeta.getContentType().contains("image") && !fileMeta.getContentType().contains("video")) {
                            showAttachmentIconAndText(attachedFile, message, mimeType);
                        }
                    }
                }
                if (isNormalAttachment(message)) {
                    attachedFile.setVisibility(View.GONE);
                    mainAttachmentLayout.setVisibility(View.GONE);
                    mainContactShareLayout.setVisibility(View.GONE);
                    chatLocation.setVisibility(View.GONE);
                    audioView.hideView(false);
                    return;
                }
            }
            if (message.isCanceled()) {
                attachmentRetry.setVisibility(View.VISIBLE);
            }
            attachmentRetry.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (Utils.isInternetAvailable(mContext)) {
                        File file = null;
                        if (MobicomSendMessageView.this.message != null && MobicomSendMessageView.this.message.getFilePaths() != null) {
                            file = new File(MobicomSendMessageView.this.message.getFilePaths().get(0));
                        }
                        if (file != null && !file.exists()) {
                            Toast.makeText(mContext, mContext.getString(R.string.file_does_not_exist), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Toast.makeText(mContext, mContext.getString(R.string.applozic_resending_attachment), Toast.LENGTH_SHORT).show();
                        mediaUploadProgressBar.setVisibility(View.VISIBLE);
                        attachmentRetry.setVisibility(View.GONE);
                        MobicomSendMessageView.this.message.setCanceled(false);
                        MobicomSendMessageView.this.messageDatabaseService.updateCanceledFlag(MobicomSendMessageView.this.message.getMessageId(), 0);
                        MobicomSendMessageView.this.conversationService.sendMessage(MobicomSendMessageView.this.message, MobicomSendMessageView.this.messageIntentClass);
                    } else {
                        Toast.makeText(mContext, mContext.getString(R.string.internet_connection_not_available), Toast.LENGTH_SHORT).show();
                    }
                }
            });
            attachmentDownloadProgressLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    attachmentView.setVisibility(View.GONE);
                    attachmentView.cancelDownload();
                    attachmentDownloadProgressLayout.setVisibility(View.GONE);
                    MobicomSendMessageView.this.message.setAttDownloadInProgress(false);
                }
            });

            preview.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (MobicomSendMessageView.this.message.getContentType() == Message.ContentType.TEXT_URL.getValue()) {
                        return;
                    }
                    if (MobicomSendMessageView.this.message.isAttachmentDownloaded()) {
                        showFullView(MobicomSendMessageView.this.message);
                        return;
                    }
                    if (!MobicomSendMessageView.this.message.isTypeOutbox() || MobicomSendMessageView.this.message.isSentToServer()) {
                        attachmentDownloadLayout.setVisibility(View.GONE);
                        attachmentView.setProressBar(mediaDownloadProgressBar);
                        attachmentView.setDownloadProgressLayout(attachmentDownloadProgressLayout);
                        attachmentView.setMessage(MobicomSendMessageView.this.message);
                        attachmentView.setVisibility(View.VISIBLE);
                        attachmentDownloadProgressLayout.setVisibility(View.VISIBLE);
                    }
                }
            });
            preview.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return false;
                }
            });
            attachmentView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    showFullView(MobicomSendMessageView.this.message);
                }
            });
            attachmentView.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    return false;
                }
            });
            if (attachedFile != null) {
                attachedFile.setOnLongClickListener(new OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        return false;
                    }
                });
            }
            String mimeType = "";
            if (messageTextView != null) {
                messageTextView.setTextColor(message.isTypeOutbox() ? Color.parseColor(alCustomizationSettings.getSentMessageTextColor()) : Color.parseColor(alCustomizationSettings.getReceivedMessageTextColor()));
                messageTextView.setLinkTextColor(message.isTypeOutbox() ? Color.parseColor(alCustomizationSettings.getSentMessageLinkTextColor()) : Color.parseColor(alCustomizationSettings.getReceivedMessageLinkTextColor()));
                if (messageTextLayout != null) {
                    messageTextLayout.setOnClickListener(null);
                }
                if (message.getContentType() == Message.ContentType.TEXT_URL.getValue()) {
                    attachedFile.setVisibility(View.GONE);
                    preview.setVisibility(View.VISIBLE);
                    messageTextView.setText(message.getMessage());
                    setRoundImg(myAvatar);
                    loadImage.setImageFadeIn(false);
                    loadImage.loadImage(message.getFileMetas().getBlobKeyString(), preview);
                    attachmentDownloadLayout.setVisibility(View.GONE);
                    mainAttachmentLayout.setVisibility(VISIBLE);
                } else if (message.getContentType() == Message.ContentType.LOCATION.getValue()) {
                    chatLocation.setLayoutParams(getImageLayoutParam(false));
                    chatLocation.setVisibility(View.VISIBLE);

                    loadImage.setImageFadeIn(false);
                    loadImage.setLoadingImage(R.drawable.applozic_map_offline_thumbnail);
                    loadImage.loadImage(LocationUtils.loadStaticMap(message.getMessage()), mapImageView);
                    messageTextView.setVisibility(View.GONE);

                    mapImageView.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Uri webpage = Uri.parse("http://api.map.baidu.com/marker?location=" + LocationUtils.getLocationFromMessage(MobicomSendMessageView.this.message.getMessage()) + "&output=html");
                            Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
                            mContext.startActivity(webIntent);
                        }
                    });
                } else if (message.getContentType() == Message.ContentType.ATTACHMENT.getValue()) {
                    mainAttachmentLayout.setVisibility(VISIBLE);
                } else if (message.getContentType() == Message.ContentType.PRICE.getValue()) {
                    messageTextView.setText(ConversationUIService.FINAL_PRICE_TEXT + message.getMessage());
                    setRoundImg(myAvatar);
                } else if ((message.getContentType() == Message.ContentType.VIDEO_MSG.getValue()) && !message.isAttachmentDownloaded()) {
                    preview.setVisibility(View.VISIBLE);
                    preview.setImageResource(R.drawable.applozic_video_default_thumbnail);
                } else if (message.getContentType() == Message.ContentType.TEXT_HTML.getValue()) {
                    messageTextView.setText(Html.fromHtml(message.getMessage()));
                    setRoundImg(myAvatar);
                } else if (message.getContentType() == Message.ContentType.RED_PACKET.getValue()) {
                    messageTextView.setText(message.getMetadata().get(ChatConfig.PACKET_MESSAGE));
                    messageTextLayout.setBackgroundResource(R.mipmap.right_red_packet);
                    setRoundImg(myAvatar);

                    messageTextLayout.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (!UserInfo.getToken().equals("")) {
                                if (UserInfo.getIsTest() == 1 && UserInfo.getIsTry() != 1) {
                                    utils.Utils.showToast(Common.IS_TEST);
                                } else {
                                    RetrofitBase.getRetrofit().create(GrabGiftRequest.class).getResult(MobicomSendMessageView.this.message.getMetadata().get(ChatConfig.PACKET_ID), UserInfo.getUsername(), UserInfo.getToken())
                                            .compose(RxHelper.<GrabGiftResponse>handleResult())
                                            .subscribe(new RxSubscribe<GrabGiftResponse>(mContext) {
                                                @Override
                                                protected void _onNext(GrabGiftResponse grabGiftResponse) {
                                                    utils.Utils.showToast(grabGiftResponse.getMsg());

                                                    GrabRedPacketSucess grabRedPacketSucess = new GrabRedPacketSucess();
                                                    grabRedPacketSucess.setRedPacketFrom(MobicomSendMessageView.this.message.getMetadata().get(ChatConfig.PACKET_FROM));
                                                    grabRedPacketSucess.setHave_get_packet_id(grabGiftResponse.getGift_rand_id());
                                                    grabRedPacketSucess.setRedPacketID(grabGiftResponse.getGift_id());
                                                    grabRedPacketSucess.setConversationId(((FragmentActivity) mContext).getIntent().getStringExtra(ConversationUIService.USER_ID));
                                                    EventBus.getDefault().post(grabRedPacketSucess);
                                                }

                                                @Override
                                                protected boolean showDialog() {
                                                    return false;
                                                }
                                            });
                                }
                            } else {
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                mContext.startActivity(intent);
                                ((Activity) mContext).overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
                            }
                        }
                    });
                } else {
                    Spannable spannable = EmoticonUtils.getSmiledText(mContext, message.getMessage(), emojiconHandler);
                    if (spannable.length() <= 300) {
                        messageTextView.setText(spannable);
                        setRoundImg(myAvatar);
                        if (mimeType != null && attachmentIcon != null) {
                            if (mimeType.startsWith("image")) {
                                attachmentIcon.setImageResource(R.drawable.applozic_ic_action_camera);
                            } else if (mimeType.startsWith("video")) {
                                attachmentIcon.setImageResource(R.drawable.applozic_ic_action_video);
                            }
                        }
                    }
                }
            }
            if (message.isContactMessage()) {
                attachedFile.setVisibility(View.GONE);
                mainAttachmentLayout.setVisibility(View.GONE);
                setupContactShareView(message, mainContactShareLayout);
                return;
            } else {
                mainContactShareLayout.setVisibility(View.GONE);
            }

            int startIndex = indexOfSearchQuery(message.getMessage());
            if (startIndex != -1) {
                final SpannableString highlightedName = new SpannableString(message.getMessage());
                highlightedName.setSpan(highlightTextSpan, startIndex, startIndex + searchString.length(), 0);
                messageTextView.setText(highlightedName);
                setRoundImg(myAvatar);
            }
        }
    }

    private void gotoGivePrize(Message message, Contact contact) {
        if (!UserInfo.getToken().equals("") && contact != null) {
            if (UserInfo.getIsTest() == 1) {
                utils.Utils.showToast("试玩账号不能打赏");
            } else {
                if (!((FragmentActivity) mContext).getIntent().getBooleanExtra("is_single", false)) {//单人聊天不能打赏
                    Intent intent = new Intent(mContext, GiveRewardActivity.class);
                    intent.putExtra("avatar", contact.getImageURL());
                    intent.putExtra("user", message.getContactIds());
                    mContext.startActivity(intent);
                }
            }
        }
    }


    private void setRoundImg(ImageView myAvatar) {
        if (myAvatar != null) {
            if (UserInfo.getToken().equals("")) {
                myAvatar.setImageResource(R.mipmap.chat_default);
            } else {
                if (UserInfo.getAvatar().equals("")) {
                    myAvatar.setImageResource(R.mipmap.chat_default);
                } else {
                    GlideHelper.loadRoundImage(getContext(), UserInfo.getAvatar(), myAvatar);
                }
            }
        }
    }

    public ViewGroup.LayoutParams getImageLayoutParam(boolean outBoxType) {
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(metrics);
        float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60, mContext.getResources().getDisplayMetrics());
        MarginLayoutParams params;
        if (outBoxType) {
            params = new LayoutParams(metrics.widthPixels + (int) wt_px * 2, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins((int) wt_px, 0, (int) wt_px, 0);
        } else {
            params = new LinearLayout.LayoutParams(metrics.widthPixels - (int) wt_px * 2, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 0, 0, 0);

        }
        return params;
    }

    private void showAttachmentIconAndText(TextView attachedFile, final Message message, final String mimeType) {

        String fileName = "";
        if (message.getFileMetas() == null && message.getFilePaths() != null) {
            fileName = message.getFilePaths().get(0).substring(message.getFilePaths().get(0).lastIndexOf("/") + 1);
        } else if (message.getFileMetas() != null) {
            fileName = message.getFileMetas().getName();
        }
        attachedFile.setTextColor(message.isTypeOutbox() ?
                Color.parseColor(alCustomizationSettings.getSentMessageTextColor()) : Color.parseColor(alCustomizationSettings.getReceivedMessageTextColor()));
        attachedFile.setText(fileName);
        attachedFile.setVisibility(View.VISIBLE);
        attachedFile.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (message.isAttachmentDownloaded()) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        Uri outputUri;
                        if (Utils.hasNougat()) {
                            outputUri = FileProvider.getUriForFile(mContext, mContext.getString(R.string.app_id) + ".fileprovider", new File(message.getFilePaths().get(0)));
                        } else {
                            outputUri = Uri.fromFile(new File(message.getFilePaths().get(0)));
                        }
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        if (intent.resolveActivity(mContext.getPackageManager()) != null) {
                            intent.setDataAndType(outputUri, mimeType);
                            mContext.startActivity(intent);
                        } else {
                            Toast.makeText(mContext, R.string.info_app_not_found_to_open_file, Toast.LENGTH_LONG).show();
                        }
                    }
                } catch (Exception e) {
                }
            }

        });
    }

    private void showPreview(Message message, ImageView preview, LinearLayout attachmentDownloadLayout) {
        imageThumbnailLoader.setImageFadeIn(false);
        imageThumbnailLoader.setLoadingImage(R.id.media_upload_progress_bar);
        imageThumbnailLoader.loadImage(message, preview);
        attachmentDownloadLayout.setVisibility(View.GONE);
    }

    private boolean isNormalAttachment(Message message) {

        if (message.getFileMetas() != null) {
            return !(message.getFileMetas().getContentType().contains("image") || message.getFileMetas().getContentType().contains("video") || message.isContactMessage());
        } else if (message.getFilePaths() != null) {
            String filePath = message.getFilePaths().get(0);
            final String mimeType = FileUtils.getMimeType(filePath);
            if (mimeType != null) {
                return !(mimeType.contains("image") || mimeType.contains("video") || message.isContactMessage());
            }
        }
        return false;
    }


    private void showFullView(Message smListItem) {
        try {
            final String mimeType = FileUtils.getMimeType(smListItem.getFilePaths().get(0));
            if (mimeType != null) {
                if (mimeType.startsWith("image")) {
                    Intent intent = new Intent(mContext, FullScreenImageActivity.class);
                    intent.putExtra(MobiComKitConstants.MESSAGE_JSON_INTENT, GsonUtils.getJsonFromObject(smListItem, Message.class));
                    ((MobiComKitActivityInterface) mContext).startActivityForResult(intent, MobiComKitActivityInterface.REQUEST_CODE_FULL_SCREEN_ACTION);
                }
                if (mimeType.startsWith("video")) {
                    if (smListItem.isAttachmentDownloaded()) {
                        Intent intentVideo = new Intent();
                        intentVideo.setAction(Intent.ACTION_VIEW);
                        Uri outputUri;
                        if (Utils.hasNougat()) {
                            outputUri = FileProvider.getUriForFile(mContext, mContext.getString(R.string.app_id) + ".fileprovider", new File(smListItem.getFilePaths().get(0)));
                        } else {
                            outputUri = Uri.fromFile(new File(smListItem.getFilePaths().get(0)));
                        }
                        intentVideo.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        if (intentVideo.resolveActivity(mContext.getPackageManager()) != null) {
                            intentVideo.setDataAndType(outputUri, "video/*");
                            mContext.startActivity(intentVideo);
                        } else {
                            Toast.makeText(mContext, R.string.info_app_not_found_to_open_file, Toast.LENGTH_LONG).show();
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
    }


    private void setupContactShareView(final Message message, LinearLayout mainContactShareLayout) {
        mainContactShareLayout.setVisibility(View.VISIBLE);
        mainContactShareLayout.setLayoutParams(getImageLayoutParam(false));
        MobiComVCFParser parser = new MobiComVCFParser();
        try {

            VCFContactData data = parser.parseCVFContactData(message.getFilePaths().get(0));
            ImageView shareContactImage = mainContactShareLayout.findViewById(R.id.contact_share_image);
            TextView shareContactName = mainContactShareLayout.findViewById(R.id.contact_share_tv_name);
            TextView shareContactNo = mainContactShareLayout.findViewById(R.id.contact_share_tv_no);
            TextView shareEmailContact = mainContactShareLayout.findViewById(R.id.contact_share_emailId);

            Button addContactButton = mainContactShareLayout.findViewById(R.id.contact_share_add_btn);
            shareContactName.setText(data.getName());

            int resId = message.isTypeOutbox() ? Color.parseColor(alCustomizationSettings.getSentMessageTextColor()) : Color.parseColor(alCustomizationSettings.getReceivedMessageTextColor());
            shareContactName.setTextColor(resId);
            shareContactNo.setTextColor(resId);
            shareEmailContact.setTextColor(resId);
            addContactButton.setTextColor(resId);

            if (data.getProfilePic() != null) {
                if (imageCache.getBitmapFromMemCache(message.getKeyString()) == null) {
                    imageCache.addBitmapToCache(message.getKeyString(), data.getProfilePic());
                }

                shareContactImage.setImageBitmap(imageCache.getBitmapFromMemCache(message.getKeyString()));
            }
            if (!TextUtils.isEmpty(data.getTelephoneNumber())) {
                shareContactNo.setText(data.getTelephoneNumber());
            } else {
                shareContactNo.setVisibility(View.GONE);
            }
            if (data.getEmail() != null) {
                shareEmailContact.setText(data.getEmail());
            } else {
                shareEmailContact.setVisibility(View.GONE);
            }


            addContactButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    Uri outputUri;
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    if (Utils.hasNougat()) {
                        outputUri = FileProvider.getUriForFile(mContext, getContext().getString(R.string.app_id) + ".fileprovider", new File(message.getFilePaths().get(0)));
                    } else {
                        outputUri = Uri.fromFile(new File(message.getFilePaths().get(0)));
                    }
                    if (intent.resolveActivity(mContext.getPackageManager()) != null) {
                        intent.setDataAndType(outputUri, "text/x-vcard");
                        mContext.startActivity(intent);
                    } else {
                        Toast.makeText(mContext, R.string.info_app_not_found_to_open_file, Toast.LENGTH_LONG).show();
                    }
                }
            });

        } catch (Exception e) {
        }

    }

    private int indexOfSearchQuery(String message) {
        if (!TextUtils.isEmpty(searchString)) {
            return message.toLowerCase(Locale.getDefault()).indexOf(
                    searchString.toLowerCase(Locale.getDefault()));
        }
        return -1;
    }
}
